package leecode.stringcompress;

public class StringCmp {
    public static void main(String[] args) {
        compressString("abbccd");
    }

    public static String compressString(String S) {
        if (S == null || S.equals("")) {
            return S;
        }
        StringBuilder sb = new StringBuilder();
        int j = 1;
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (i == 0) {
                sb.append(c);
                continue;
            }
            if (c == sb.charAt(sb.length() - 1)) {
                j++;
                continue;
            }
            sb.append(j);
            sb.append(c);
            j = 1;
        }
        sb.append(j);
        return sb.length() < S.length() ? sb.toString() : S;
    }

    public static String compressStringS(String S) {
        if (S == null || S.equals("")) {
            return S;
        }
        int start = 0;
        int end = 0;

        StringBuilder sb = new StringBuilder();
        int j = 1;
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (i == 0) {
                sb.append(c);
                continue;
            }
            if (c == sb.charAt(sb.length() - 1)) {
                j++;
                continue;
            }
            sb.append(j);
            sb.append(c);
            j = 1;
        }
        sb.append(j);
        return sb.length() < S.length() ? sb.toString() : S;
    }
}
